<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>标签管理 - 后台管理</title>
  <link rel="stylesheet" href="/static/base.css">
  <link rel="stylesheet" href="/static/components.css">
  <link rel="stylesheet" href="/static/pages.css">
  <link rel="stylesheet" href="/static/admin/admin.css">
</head>
<body>
  <div class="admin-layout">
    <!-- 顶部导航 -->
    <div class="admin-header">
      <h2>标签管理</h2>
      <div>
        <button class="btn" onclick="location.href='/'">返回前台</button>
        <button class="btn" onclick="logout()">退出</button>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="admin-main">
      <!-- 左侧导航（公共组件注入） -->
      <div class="admin-sidebar"></div>

      <!-- 右侧内容区域 -->
      <div class="admin-content">
        <div class="content-page active">
          <h3>标签管理</h3>
          <p class="page-description">默认显示最新交易日的股票及行情，可为任意股票设置"长期标签"（与交易日无关）。</p>

          <div class="content-card">
            <div style="display:flex; gap:12px; align-items:center; flex-wrap:wrap;">
              <input id="q" type="text" class="form-control" placeholder="按代码/名称过滤..." style="width:240px;">
              <button class="btn" onclick="reloadStocks()">查询</button>
              <button class="btn" onclick="resetFilters()">清空</button>
            </div>
          </div>

          <div class="content-card">
            <h4>股票列表</h4>
            <div class="table-container performance-table-container">
              <table class="performance-table">
                <thead>
                  <tr>
                    <th>代码</th>
                    <th>名称</th>
                    <th>最新价</th>
                    <th>行业</th>
                    <th>概念</th>
                    <th>已有标签</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody id="stock-body"></tbody>
              </table>
            </div>
            <div style="display:flex; justify-content:space-between; align-items:center; margin-top:8px;">
              <div style="display:flex; gap:8px; align-items:center;">
                <button class="btn" onclick="prevPage()">上一页</button>
                <div id="pager-info" style="color:#6c757d;">-</div>
                <button class="btn" onclick="nextPage()">下一页</button>
              </div>
              <div style="display:flex; gap:8px; align-items:center;">
                <span>跳转到:</span>
                <input id="page-input" type="number" min="1" style="width:60px; padding:4px 8px;" placeholder="页码">
                <button class="btn" onclick="goToPage()">跳转</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 标签侧栏 -->
  <div id="label-drawer" class="content-card" style="position:fixed; right:16px; top:80px; width:360px; max-width:90vw; z-index:1000; display:none;">
    <h4>编辑标签</h4>
    <div class="form-group">
      <label class="form-label">股票</label>
      <div id="label-stock" style="color:#2c3e50; font-weight:600;">-</div>
    </div>
    <div class="form-group">
      <label class="form-label">标签名称</label>
      <input id="label-name" type="text" class="form-control" placeholder="例如：白马股/高成长/稳健...">
    </div>
    <div class="form-group">
      <label class="form-label">标签类型（可选）</label>
      <input id="label-type" type="text" class="form-control" placeholder="手工/策略/行业...">
    </div>
    <div class="form-group">
      <label class="form-label">置信度</label>
      <input id="label-confidence" type="number" class="form-control" value="100" min="0" max="100">
    </div>
    <div class="form-group">
      <button class="btn btn-primary" onclick="saveLabel()">保存标签</button>
      <button class="btn" onclick="closeLabelPanel()" style="margin-left:8px;">关闭</button>
    </div>

    <h4 style="margin-top:16px;">已有标签</h4>
    <div id="label-list" style="display:flex; flex-wrap:wrap; gap:8px;"></div>
  </div>

  <script src="/static/admin/components/sidebar.js"></script>
  <script>
    // 标签管理相关变量
    let current = { id:'', name:'' };
    let pager = { page:1, page_size:20, total:0 };

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
      reloadStocks();
      injectAdminSidebar('/admin/label-management');
    });

    // 标签管理相关函数
    function resetFilters(){
      document.getElementById('q').value = '';
      reloadStocks();
    }

    async function reloadStocks(){
      const q = document.getElementById('q').value.trim();
      const params = new URLSearchParams({ page: pager.page, page_size: pager.page_size });
      if(q) params.set('q', q);
      
      try {
        const resp = await fetch('/admin/api/labels/stocks?' + params.toString());
        const data = await resp.json();
        
        const body = document.getElementById('stock-body');
        body.innerHTML = '';
        
        if(data && data.success){
          pager.total = data.total || 0;
          pager.page = data.page || 1;
          pager.page_size = data.page_size || 20;
          document.getElementById('pager-info').textContent = `第 ${pager.page} / ${Math.max(1, Math.ceil(pager.total/pager.page_size))} 页，共 ${pager.total} 条`;
          
          for(const s of (data.data||[])){
            const tr = document.createElement('tr');
            tr.innerHTML = `
              <td><span class="stock-code">${s.security_id}</span></td>
              <td><span class="stock-name">${s.security_name||'-'}</span></td>
              <td><span class="stock-price">${s.latest_price ? s.latest_price.toFixed(3) : '-'}</span></td>
              <td><span class="stock-industry">${s.industry||'-'}</span></td>
              <td><span class="stock-concepts" title="${s.concepts||'-'}">${s.concepts||'-'}</span></td>
              <td><div id="tags-${s.security_id}" class="tags-container"></div></td>
              <td><button class="btn btn-sm btn-primary" onclick="openLabelPanel('${s.security_id}','${s.security_name||''}')">设置标签</button></td>
            `;
            body.appendChild(tr);
            loadLabels(s.security_id);
          }
        } else {
          console.error('API返回错误:', data.error);
        }
      } catch (error) {
        console.error('加载股票列表失败:', error);
      }
    }

    function prevPage(){ if(pager.page>1){ pager.page--; reloadStocks(); } }
    function nextPage(){ const maxPage = Math.max(1, Math.ceil(pager.total/pager.page_size)); if(pager.page<maxPage){ pager.page++; reloadStocks(); } }
    
    function goToPage(){
      const input = document.getElementById('page-input');
      const page = parseInt(input.value);
      const maxPage = Math.max(1, Math.ceil(pager.total/pager.page_size));
      if(page >= 1 && page <= maxPage){
        pager.page = page;
        reloadStocks();
        input.value = '';
      } else {
        alert(`请输入1-${maxPage}之间的页码`);
      }
    }

    async function loadLabels(securityId){
      try{
        const resp = await fetch('/admin/api/labels/list?security_id=' + encodeURIComponent(securityId));
        const data = await resp.json();
        const wrap = document.getElementById('tags-' + securityId);
        if(!wrap) return;
        wrap.innerHTML = '';
        (data.labels || []).forEach(l => {
          const tag = document.createElement('span');
          tag.textContent = l.label;
          tag.className = 'tag-badge';
          tag.title = `类型:${l.label_type||''} 置信度:${l.confidence||0}`;
          const del = document.createElement('a');
          del.textContent = '×';
          del.className = 'tag-delete';
          del.onclick = () => deleteLabel(l.id, securityId);
          tag.appendChild(del);
          wrap.appendChild(tag);
        });
      }catch(e){ console.error(e); }
    }

    function openLabelPanel(id, name){
      if(id){ current = { id, name }; }
      document.getElementById('label-stock').textContent = `${current.id} ${current.name||''}`;
      document.getElementById('label-name').value='';
      document.getElementById('label-type').value='手工';
      document.getElementById('label-confidence').value='100';
      document.getElementById('label-drawer').style.display = 'block';
      if(current.id){ loadLabels(current.id); }
    }

    function closeLabelPanel(){
      document.getElementById('label-drawer').style.display = 'none';
    }

    async function saveLabel(){
      const label = document.getElementById('label-name').value.trim();
      const type = document.getElementById('label-type').value.trim();
      const conf = Number(document.getElementById('label-confidence').value||100);
      if(!current.id){ alert('请先选择股票'); return; }
      if(!label){ alert('请输入标签名称'); return; }
      try{
        const resp = await fetch('/admin/api/labels/upsert', {
          method:'POST', headers:{'Content-Type':'application/json'},
          body: JSON.stringify({ security_id: current.id, label, label_type: type, confidence: conf })
        });
        const data = await resp.json();
        if(data && data.success){
          loadLabels(current.id);
          alert('已保存标签');
        } else {
          alert('保存失败: ' + (data.error||'未知错误'));
        }
      }catch(e){ alert('保存失败'); }
    }

    async function deleteLabel(id, securityId){
      if(!confirm('确定删除该标签吗？')) return;
      try{
        const resp = await fetch('/admin/api/labels/delete', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ id }) });
        const data = await resp.json();
        if(data && data.success){ loadLabels(securityId); }
      }catch(e){ console.error(e); }
    }

    // 退出登录
    async function logout(){
      try{ 
        await fetch('/admin/logout', {method:'POST'}); 
        location.href='/admin/login'; 
      }catch(e){ 
        location.href='/admin/login'; 
      }
    }
  </script>

  <style>
    /* 标签管理页面专用样式 */
    
    /* 表格容器样式 */
    .performance-table-container {
      max-height: 60vh;
      overflow-y: auto;
      border: 1px solid #e9ecef;
      border-radius: 8px;
      background: white;
    }

    /* 股票代码样式 */
    .stock-code {
      font-family: 'Courier New', monospace;
      font-weight: 600;
      color: #2c3e50;
      background: #f8f9fa;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 13px;
    }

    /* 股票名称样式 */
    .stock-name {
      font-weight: 600;
      color: #2c3e50;
      font-size: 14px;
    }

    /* 股票价格样式 */
    .stock-price {
      font-family: 'Courier New', monospace;
      font-weight: 600;
      color: #28a745;
      font-size: 14px;
    }

    /* 股票行业样式 */
    .stock-industry {
      color: #6c757d;
      font-size: 13px;
      background: #e9ecef;
      padding: 2px 6px;
      border-radius: 3px;
    }

    /* 股票概念样式 */
    .stock-concepts {
      color: #495057;
      font-size: 12px;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      max-width: 200px;
    }

    /* 标签容器样式 */
    .tags-container {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
      max-width: 250px;
    }

    /* 标签样式 */
    .tag-badge {
      display: inline-flex;
      align-items: center;
      padding: 3px 8px;
      background: linear-gradient(135deg, #e3f2fd, #bbdefb);
      color: #1976d2;
      border-radius: 12px;
      font-size: 11px;
      font-weight: 500;
      border: 1px solid #90caf9;
      transition: all 0.2s ease;
    }

    .tag-badge:hover {
      background: linear-gradient(135deg, #bbdefb, #90caf9);
      transform: translateY(-1px);
    }

    /* 标签删除按钮样式 */
    .tag-delete {
      margin-left: 4px;
      color: #666;
      cursor: pointer;
      font-weight: bold;
      font-size: 12px;
      transition: color 0.2s ease;
    }

    .tag-delete:hover {
      color: #dc3545;
    }

    /* 操作按钮样式 */
    .btn-sm {
      padding: 6px 12px;
      font-size: 12px;
      border-radius: 6px;
    }

    /* 分页信息样式 */
    #pager-info {
      font-weight: 500;
      font-size: 14px;
    }

    /* 标签侧栏样式 */
    #label-drawer {
      box-shadow: 0 4px 20px rgba(0,0,0,0.15);
      border-radius: 12px;
      padding: 20px;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      .performance-table-container {
        max-height: 50vh;
      }
      
      .stock-concepts {
        max-width: 150px;
      }
      
      .tags-container {
        max-width: 200px;
      }

      #label-drawer {
        width: 95vw;
        right: 2.5vw;
      }
    }
  </style>
</body>
</html>
